<template>
  <div>
    <!-- 资金返利对账表生成 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="qjhRebateStatementGenerate"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onRowSelectChange="selectChangeHandle"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="primary" @click="addHandle">生成对账</el-button>
          <multiuse-button size="small" type="primary" :click="sendHandle" :disabled="isIssue">下 发</multiuse-button>
          <multiuse-button size="small" type="primary" :click="exportHandle">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <!-- 经销商查询 -->
    <BaseDialog :visible.sync="isDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OwnerSearch :rowData="formData" @close="emitCloseHandler" />
    </BaseDialog>

    <BaseDialog :visible.sync="isAdd" :title="'对账单生成'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <AddModel :rowData="formData" @close="emitCloseHandler1" />
    </BaseDialog>

    <Drawer :visible.sync="visible" :title="'明细'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <SonModel :type="'show'" :rowData="formData" @close="emitCloseHandler" />
    </Drawer>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getRegion } from '@/api/omFinance';
import { exportExcelFile } from '@/utils/index';
import { queryList, delById, sendData, exportExcel,exporturl } from '@/api/omFinance/RebateManage/RebateStatementGenerate';
import AddModel from './AddModel';
import SonModel from './SonModel';
import OwnerSearch from '../OwnerSearch';

export default {
  name: 'RebateStatementGenerate',
  mixins: [dictionary],

  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchParams: {
        searchType: 3
      },
      fetchApi: queryList,
      formData: {},
      verifyIds: [],
      isAdd: false,
      isIssue: true,
      isDealer: false,
      visible: false,
      exportLoading: false
    };
  },
  components: {
    AddModel,
    SonModel,
    OwnerSearch
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getDeptData();
  },
  methods: {
    //加载事业部数据
    async getDeptData() {
      const res = await getRegion({});
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'deptId').itemList = res.data.map(x => ({ value: x.id, text: x.orgName }));
      }
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    selectChangeHandle(rows) {
      this.verifyIds = [];
      if (rows.length > 0) {
        this.isIssue = !rows.every(x => x.status == 60841001);
        rows.map(x => {
          this.verifyIds.push(x.id);
        });
        return;
      }
      this.isIssue = true;
    },
    seacherFun() {
      this.isDealer = true;
    },
    emitCloseHandler1(val, type) {
      this.isAdd = val;
      if (type == 'refresh') {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    emitCloseHandler(val, data) {
      this.isDealer = val;
      this.visible = val;
      if (data) {
        let dealerCodes = [];
        let dealerNames = [];
        data.map(x => {
          dealerCodes.push(x.dealerCode);
          dealerNames.push(x.dealerName);
        });
        this.topFilterList.find(x => x.fieldName == 'dealerCode').initialValue = dealerCodes.toString();
      }
    },
    addHandle() {
      this.isAdd = true;
    },
    detailHandle(row) {
      this.formData = row;
      this.visible = true;
    },
    async delHandle(row) {
      await this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let res = await delById(row.id);
          if (res.resultCode == 200) {
            this.$notify.success({
              title: '提示信息',
              message: '删除成功'
            });
            this.fetchParams = Object.assign({}, this.fetchParams);
          }
        })
        .catch(() => {});
    },
    // 下发
    async sendHandle() {
      await this.$confirm('是否下发?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let res = await sendData({ verifyIds: this.verifyIds });
          if (res.resultCode == 200) {
            this.$notify.success({
              title: '提示信息',
              message: '下发成功'
            });
            this.fetchParams = Object.assign({}, this.fetchParams);
            this.isIssue = true;
          }
        })
        .catch(() => {});
    },
    // 导出
    async exportHandle() {
        let json = Object.assign({}, { CODE: 'CODE_00000229' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;

      //     exportExcel(this.fetchParams)
      //       .then(response => {
      //         exportExcelFile(response.data, '资金返利对账表查询');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '事业部',
          fieldName: 'deptId',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        },

        {
          type: 'SELECT',
          label: '对账分类',
          fieldName: 'verifyType',
          placeholder: '请选择',
          itemList: this.createDictList('6086')
        },
        {
          type: 'RANGE_DATE',
          label: '生成日期',
          fieldName: 'createdAtBeginDate|createdAtEndDate',
          initialValue: [],
          dateType: 'exactdaterange'
        },
        {
          type: 'SELECT',
          label: '动力形式',
          fieldName: 'powerType',
          placeholder: '请选择',
          itemList: this.createDictList('6008')
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  明细
                </multiuse-button>
                <multiuse-button size="mini" type="text" onClick={() => this.delHandle(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '事业部',
          dataIndex: 'deptName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '账户资金所属公司',
          dataIndex: 'orgCompanyName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6084'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '6084')}</span>;
          }
        },
        {
          title: '动力形式',
          dataIndex: 'powerType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6008'),
          render: props => {
            return <span>{this.createDictText(props.row.powerType, '6008')}</span>;
          }
        },
        {
          title: '对账分类',
          dataIndex: 'verifyType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6086'),
          render: props => {
            return <span>{this.createDictText(props.row.verifyType, '6086')}</span>;
          }
        },
        {
          title: '对账单名称',
          dataIndex: 'verifyName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '整车款余额',
          dataIndex: 'vehicleAccountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '整车返利余额',
          dataIndex: 'vehicleRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '备件款余额',
          dataIndex: 'partAccountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '备件返利余额',
          dataIndex: 'partRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '建店保证金余额',
          dataIndex: 'depositAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '其他类应收款项',
          dataIndex: 'otherInAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '其他类应付款项',
          dataIndex: 'otherOutAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '生成日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd'
        }
      ];
    }
  }
};
</script>
